package com.xiaoye.qbproject.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaoye.qbproject.domain.QbUser;
import com.xiaoye.qbproject.service.web.TokenService;
import com.xiaoye.qbproject.constant.UserConstants;
import com.xiaoye.qbproject.domain.model.LoginUser;
import com.xiaoye.qbproject.exception.user.UserNotExistsException;
import com.xiaoye.qbproject.exception.user.UserPasswordNotMatchException;
import com.xiaoye.qbproject.redis.RedisCache;
import com.xiaoye.qbproject.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class LoginService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private QbUserService qbUserService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        // 登录前置校验
        loginPreCheck(username, password);
        // 查询账号密码
        QbUser qbUser = qbUserService.getOne(Wrappers.<QbUser>lambdaQuery()
                .eq(QbUser::getUsername, username)
                .eq(QbUser::getPassword, password)
        );
        if (qbUser == null) {
            throw new UserNotExistsException();
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(qbUser);
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public void logout(HttpServletRequest request){
        tokenService.logout(request);
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

    }

}
